package com.crazy.common.form;

import static com.crazy.common.form.Token.TOKEN;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.crazy.common.Tools;

/**
 * 令牌处理拦截器
 * 
 * @author zhang weiwei
 */
public class TokenHandlerInterceptor extends HandlerInterceptorAdapter {
	HttpServletRequest request;
	HttpSession session;

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			Method method = handlerMethod.getMethod();
			Token token = method.getAnnotation(Token.class);
			if (token != null) {
				this.request = request;
				session = request.getSession(false);
				boolean save = token.save();
				if (save) {
					session.setAttribute(TOKEN, Tools.getUUID());
				}
				boolean remove = token.remove();
				if (remove) {
					if (this.isRepeatSubmitted()) {
						return false;
					}
					session.removeAttribute(TOKEN);
				}
			}
		}
		return true;
	}

	private boolean isRepeatSubmitted() {
		String sessionToken = (String) session.getAttribute(TOKEN);
		if (sessionToken == null) {
			return true;
		}
		String requestToken = request.getParameter(TOKEN);
		if (requestToken == null) {
			return true;
		}
		if (!sessionToken.equals(requestToken)) {
			return true;
		}
		return false;
	}
}
